package com.yueban.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.yueban.R;
import com.yueban.adapter.ChoosePictureAdapter;
import com.yueban.fragment.MapFragment;
import com.yueban.model.BaseResponse;
import com.yueban.net.NetWorkController;
import com.yueban.util.DialogUtil;
import com.yueban.util.ImageUtils;
import com.yueban.util.SPManager;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public class ReleaseActivity extends AppCompatActivity implements MapFragment.OnFragmentInteractionListener {

    private EditText editContent;
    private GridView choosePictureGrid;
    private TextView chooseDate;
    private TextView chooseCategory;
    private TextView chooseAddress;
    private TextView address;
    private Button submit;
    private ProgressBar progressBar;
    private ChoosePictureAdapter pictureAdapter;

    private int category = 1;
    private boolean hasChosenCategory;
    private boolean hasChosenDate;
    private List<Bitmap> thumbnail;
    private List<byte[]> pictures;
    private static final int RESULT_LOAD_IMAGE = 0x1001;
    private static final int RESULT_CAMERA_IMAGE = 0x1002;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release);

        thumbnail = new ArrayList<>();
        thumbnail.add(BitmapFactory.decodeResource(getResources(), R.drawable.icon_addpic_focused));
        initView();
    }

    private void initView() {

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_release);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        //添加返回键
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle("发布活动，招募队友");
        }
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        editContent = (EditText) findViewById(R.id.editContent);
        choosePictureGrid = (GridView) findViewById(R.id.choosePictureGrid);
        chooseDate = (TextView) findViewById(R.id.chooseDate);
        chooseCategory = (TextView) findViewById(R.id.chooseCategory);
        chooseAddress = (TextView) findViewById(R.id.chooseAddress);
        address = (TextView) findViewById(R.id.address);
        submit = (Button) findViewById(R.id.submit);
        progressBar = (ProgressBar) findViewById(R.id.release_progress);

        //加载mapView的fragment
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.mapViewFragment, new MapFragment());
        transaction.commit();

        //创建并注册监听器
        MyOnClickListener myOnClickListener = new MyOnClickListener();
        submit.setOnClickListener(myOnClickListener);
        chooseDate.setOnClickListener(myOnClickListener);
        chooseCategory.setOnClickListener(myOnClickListener);
        chooseAddress.setOnClickListener(myOnClickListener);
        address.setOnClickListener(myOnClickListener);
        pictureAdapter = new ChoosePictureAdapter(ReleaseActivity.this, thumbnail);
        choosePictureGrid.setAdapter(pictureAdapter);
        choosePictureGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == thumbnail.size() - 1) { //点击了添加图片
                    if (thumbnail.size() == 10) {
                        Snackbar.make(view, "最多添加9幅图片哦", Snackbar.LENGTH_LONG)
                                .setAction("", null).show();
                        return;
                    }
                    showPopueWindow();
                }
            }
        });
    }

    @Override
    public void onFragmentInteraction(String address) {
        this.address.setText(address);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == RESULT_LOAD_IMAGE && null != data) {
                Uri uri = data.getData();
                try {
                    //获取尺寸和质量压缩过的bitmap
                    Bitmap bitmap = ImageUtils.getBitmapFromUri(ReleaseActivity.this, uri);
                    //显示缩略图
                    thumbnail.add(thumbnail.size() - 1, ThumbnailUtils.extractThumbnail(bitmap, 64, 64));
                    pictureAdapter.notifyDataSetChanged();

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    if (pictures == null)
                        pictures = new LinkedList<>();
                    pictures.add(baos.toByteArray());
                    baos.close();
                } catch (Exception e) {
                    Toast.makeText(ReleaseActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                }
            } else if (requestCode == RESULT_CAMERA_IMAGE && null != data) {

            }
        }
    }

    //自定义监听器类
    private class MyOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.chooseAddress:
                case R.id.address:
                    toInputAddress();
                    break;
                case R.id.chooseDate:
                    toChooseDate();
                    break;
                case R.id.chooseCategory:
                    toChooseCategory();
                    break;
                case R.id.choosePictureGrid:
                    break;
                case R.id.submit:
                    submitActivity();
                    break;
                default:
                    break;
            }
        }

        //弹出输入地点窗口
        private void toInputAddress() {
            final EditText editText = new EditText(ReleaseActivity.this);
            DialogUtil.showInputDialog(ReleaseActivity.this, "输入地点",
                    editText, "确定", "取消",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            address.setText(editText.getText().toString());
                        }
                    }, null);
        }

        //弹出选择日期窗口
        private void toChooseDate() {
            DialogUtil.showDateDialog(ReleaseActivity.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    monthOfYear++;
                    String date = "" + year + " - " + monthOfYear + " - " + dayOfMonth;
                    chooseDate.setText(date);
                    hasChosenDate = true;
                }
            });
        }

        //弹出选择类别窗口
        private void toChooseCategory() {
            final String[] items = getResources().getStringArray(R.array.category);
            AlertDialog.Builder builder = new AlertDialog.Builder(ReleaseActivity.this);
            builder.setTitle("活动类别");
            final int temp = category;
            builder.setSingleChoiceItems(items, category, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    category = which;
                }
            });
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String str = items[category];
                    chooseCategory.setText(str);
                    hasChosenCategory = true;
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    category = temp;
                }
            });
            builder.create();
            builder.show();
        }

        //上传数据
        private void submitActivity() {
            if (editContent.getText().toString().trim().isEmpty()) {
                Snackbar.make(submit, "写点什么吧", Snackbar.LENGTH_LONG)
                        .setAction("", null).show();
                return;
            }
            if (!hasChosenCategory) {
                Snackbar.make(submit, "请选择活动类别", Snackbar.LENGTH_LONG)
                        .setAction("", null).show();
                return;
            }
            if (!hasChosenDate) {
                Snackbar.make(submit, "请选择截止日期", Snackbar.LENGTH_LONG)
                        .setAction("", null).show();
                return;
            }
            showProgressBar(true);
            SPManager spManager = new SPManager(getApplicationContext());
            //开启异步任务,上传数据
            NetWorkController netWorkController = new NetWorkController();
            netWorkController.submitActivity(editContent.getText().toString().trim(),
                    chooseDate.getText().toString(),
                    category + "",
                    address.getText().toString(),
                    pictures, spManager.getUserId())
                    .subscribe(new Observer<BaseResponse>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull BaseResponse baseResponse) {
                            if (baseResponse.getStatus() == 0) {
                                Snackbar.make(submit, "发布成功", Snackbar.LENGTH_LONG)
                                        .setAction("", null).show();
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        finish();
                                    }
                                }, 500);
                            } else {
                                Toast.makeText(ReleaseActivity.this, baseResponse.getMessage(), Toast.LENGTH_LONG).show();
                                showProgressBar(false);
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            showProgressBar(false);
                            Toast.makeText(ReleaseActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }

    }

    //显示进度条
    private void showProgressBar(Boolean show) {
        submit.setVisibility(show ? View.GONE : View.VISIBLE);
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    //注册弹出菜单
    public void showPopueWindow() {
        View popView = View.inflate(ReleaseActivity.this, R.layout.popue_window_camera, null);
        Button bt_album = (Button) popView.findViewById(R.id.btn_pop_album);
        Button bt_camera = (Button) popView.findViewById(R.id.btn_pop_camera);
        Button bt_cancle = (Button) popView.findViewById(R.id.btn_pop_cancel); //获取屏幕宽高
        int weight = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels / 3;
        final PopupWindow popupWindow = new PopupWindow(popView, weight, height);
        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        popupWindow.setFocusable(true);
        popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        //点击外部popueWindow消失
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        bt_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, RESULT_LOAD_IMAGE);
                popupWindow.dismiss();
            }
        });
        bt_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //takeCamera(RESULT_CAMERA_IMAGE);
                popupWindow.dismiss();
            }
        });
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        //popupWindow消失屏幕变为不透明
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        //popupWindow出现屏幕变为半透明
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 50);
    }


}
